viewaster-popup<!-- 幸运抽奖 -->
<template>
  <view>
    <lucky-wheel
      ref="luckyWheelRef"
      :bg-image="bgImage"
      :award-list="awardList"
      :award-index="awardIndex"
      @start="start"
      @success="success"
      @setProbability="setProbability"
    />

    <aster-popup
      ref="setPopupRef"
      :show="showPopup"
      bgColor="#fff"
      mode="bottom"
      round="20rpx"
      @close="closePopup()"
    >
      <view class="popup">
        <view>
          <uni-row class="popup__title">
            <uni-col :span="12" class="popup__col">
              <span>奖品名称</span>
            </uni-col>
            <uni-col :span="12" class="popup__col">
              <span>中奖率</span>
            </uni-col>
          </uni-row>
          <uni-row class="popup__content" v-for="(item, index) in popupForm" :key="index">
            <view v-if="index != 4">
              <uni-col :span="12">
                <uni-easyinput v-model="item.name" :clearable="false" />
              </uni-col>
              <uni-col :span="12">
                <uni-easyinput v-model="item.probability" />
              </uni-col>
            </view>
          </uni-row>
        </view>
        <view class="popup__btn">
          <button @click="reset" size="mini" style="background-color: #f5f5f5">重置</button>
          <button @click="cancel" size="mini" style="background-color: #f5f5f5">取消</button>
          <button @click="average" size="mini" style="background-color: #007aff; color: #fff">
            公平
          </button>
          <button @click="submit" size="mini" style="background-color: #ff6a6c; color: #fff">
            提交
          </button>
        </view>
      </view>
    </aster-popup>

    <aster-popup
      ref="fireworkPopupRef"
      :show="showFirework"
      bgColor="transparent"
      mode="bottom"
      :closeable="true"
      closeableColor="#fff"
      @close="closeFirework()"
    >
      <view class="firework">
        <firework
          ref="fireworkRef"
          bg-color="transparent"
          :title="awardTitle"
          title-color="#fff"
          @done="done"
        />
      </view>
    </aster-popup>
  </view>
</template>
<script setup lang="ts">
  import LuckyWheel from '@/components/lucky/lucky-wheel.vue';
  import AsterPopup from '@/components/common/aster-popup.vue';
  import Firework from '@/components/firework/firework.vue';
  import { LuckyModel } from '@/services/model/coinModel';
  import { onLoad } from '@dcloudio/uni-app';
  import { ref } from 'vue';
  import { deepClone } from '@/utils';

  const luckyWheelRef = ref();
  // 背景图
  const bgImage = ref('../../static/images/lucky/bg.png');
  // 中奖索引
  const awardIndex = ref(0);
  // 取值模式, true-后端, false-前端
  const mode = ref(false);
  // 抽奖列表
  const awardList = ref<LuckyModel[]>([]);
  // 点击次数
  const clickTimes = ref(0);
  const showPopup = ref(false);
  const popupForm: any = ref();
  // 烟花
  const fireworkRef = ref();
  const awardTitle = ref('');
  const showFirework = ref(false);

  onLoad(() => {
    init();
  });

  const init = () => {
    // 获取抽奖列表
    awardList.value = [
      {
        img: '../../static/images/lucky/px.png',
        name: '跑鞋',
        probability: 40,
      },
      {
        img: '../../static/images/lucky/xs.png',
        name: '香水',
        probability: 50,
      },
      {
        img: '../../static/images/lucky/kh.png',
        name: '口红',
        probability: 60,
      },
      {
        img: '../../static/images/lucky/hb.png',
        name: '红包',
        probability: 25,
      },
      {
        img: '../../static/images/lucky/begin.png',
        name: '',
        probability: 0,
      },
      {
        img: '../../static/images/lucky/jz.png',
        name: '戒指',
        probability: 60,
      },
      {
        img: '../../static/images/lucky/ez.png',
        name: '耳饰',
        probability: 40,
      },
      {
        img: '../../static/images/lucky/xl.png',
        name: '项链',
        probability: 15,
      },
      {
        img: '../../static/images/lucky/sz.png',
        name: '手镯',
        probability: 10,
      },
    ];
  };

  // 开始抽奖
  const start = () => {
    // 获取中奖索引
    if (mode.value) {
      // 从后端获取
      awardIndex.value = awardIndex.value || 0;
    } else {
      awardIndex.value = prizeDraw();
      console.log(awardIndex.value);
    }
    luckyWheelRef.value.begin();
  };

  // 抽奖结果
  const prizeDraw = () => {
    let total = 0;
    const weightList: any = awardList.value.map((item) => {
      if (item.probability) {
        total += item.probability;
        return item.probability;
      } else {
        return 0;
      }
    });
    let result = 0;
    let random = Math.random() * total;
    for (let i = 0, len = weightList.length; i < len; i++) {
      random -= weightList[i];
      if (random <= 0) {
        result = i;
        break;
      }
    }
    return result;
  };

  const success = (index: number) => {
    awardTitle.value = '恭喜获得：' + awardList.value[index].name;
    showFirework.value = true;
    setTimeout(() => {
      run();
    }, 1000);
    init();
  };

  const run = () => {
    const duration = 15 * 1000;
    const animationEnd = Date.now() + duration;
    const defaults = {
      startVelocity: 30,
      spread: 360,
      ticks: 60,
      zIndex: 0,
    };

    function randomInRange(min: number, max: number) {
      return Math.random() * (max - min) + min;
    }

    const interval: any = setInterval(function () {
      const timeLeft = animationEnd - Date.now();

      if (timeLeft <= 0) {
        return clearInterval(interval);
      }

      const particleCount = 50 * (timeLeft / duration);
      // since particles fall down, start a bit higher than random
      fireworkRef.value.play(
        Object.assign({}, defaults, {
          particleCount,
          origin: {
            x: randomInRange(0.1, 0.3),
            y: Math.random() - 0.2,
          },
        }),
      );
      fireworkRef.value.play(
        Object.assign({}, defaults, {
          particleCount,
          origin: {
            x: randomInRange(0.7, 0.9),
            y: Math.random() - 0.2,
          },
        }),
      );
    }, 250);
  };

  const done = () => {
    closeFirework();
  };

  const closeFirework = () => {
    showFirework.value = false;
  };

  const setProbability = () => {
    console.log('点击次数', clickTimes.value);
    if (clickTimes.value > 2) {
      showPopup.value = true;
      popupForm.value = deepClone(awardList.value);
    } else {
      clickTimes.value++;
    }
  };

  // 关闭popup
  const closePopup = () => {
    showPopup.value = false;
    clickTimes.value = 0;
  };
  // 重置
  const reset = () => {
    init();
  };
  // 取消
  const cancel = () => {
    closePopup();
  };
  // 平均
  const average = () => {
    popupForm.value.map((item: any) => {
      item.probability = 25;
      return item;
    });
  };
  // 提交
  const submit = () => {
    console.log('submit');
    awardList.value = deepClone(popupForm.value);
    closePopup();
  };
</script>
<style lang="scss" scoped>
  .popup {
    padding: 20rpx;

    &__title {
      padding: 10rpx;
      font-size: 32rpx;
    }

    &__col {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    &__content {
      padding: 10rpx;
    }

    &__btn {
      padding: 10rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .firework {
    height: 100vh;
  }
</style>
